﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using FireBillBook.Core.Entities;
using FireBillBook.Core.Repos.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace FireBillBook.Core.Repos
{
    public class PlatformStore : IPlatformStore
    {
        private BillDbContext _db;
        public PlatformStore(BillDbContext context)
        {
            _db = context;
        }

        public async Task DeleteAsync(string name)
        {
            var old = await _db.TradingPlatforms.AsQueryable().FirstOrDefaultAsync(a => a.Name == name);
            if(old == null)
            {
                return;
            }

            _db.TradingPlatforms.Remove(old);

            await _db.SaveChangesAsync();
        }

        public async Task<List<TradingPlatform>> GetAllSync()
        {
            return await _db.TradingPlatforms.AsNoTracking().ToListAsync();
        }

        public async Task<TradingPlatform> GetByNameAsync(string name)
        {
            return await _db.TradingPlatforms.AsNoTracking().FirstOrDefaultAsync(a => a.Name == name);
        }

        public async Task SaveAsync(TradingPlatform platform)
        {
            var old = await _db.TradingPlatforms.AsQueryable().FirstOrDefaultAsync(a => a.Name == platform.Name);
            if (old == null)
            {
                _db.TradingPlatforms.Add(platform);
            }
            else
            {
                old.DisplayName = platform.DisplayName;
                old.PlatformServiceKey = platform.PlatformServiceKey;
            }

            await _db.SaveChangesAsync();
        }
    }
}
